package jaxb.cow;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JaxbUtils
{
    
    public static void obj2xml(Object o, String filePath)
    {
        try
        {
            File file = new File(filePath);
            JAXBContext jaxbContext = JAXBContext.newInstance(o.getClass());
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            jaxbMarshaller.marshal(o, file);
            jaxbMarshaller.marshal(o, System.out);
        }
        catch (JAXBException e)
        {
            e.printStackTrace();
        }
    }
    
    /**
     * <p>根据文件名称,将xml读取到object中</p>
     * <p>默认目录为PathUtils.getExcelTemplatePath()</p>
     * @param c 类信息
     * @param fileName 文件名(不含路径)
     * @author shenjunjie
     * @date [2014-7-3]
     */
    public static <T> T xml2Obj(Class<T> c, String fileName)
    {
        String filePath = PathUtils.getExcelTemplatePath();
        File file = new File(filePath + File.separator + fileName);
        return xml2Obj(file, c);
    }
    
    /**
     * <p>根据文件路径,将xml读取到object中</p>
     * @param c 类信息
     * @param fileName 文件名路径
     * @author shenjunjie
     * @date [2014-7-3]
     */
    public static <T> T xml2Obj(String filePath, Class<T> c)
    {
        File file = new File(filePath);
        return xml2Obj(file, c);
    }
    
    @SuppressWarnings("unchecked")
	public static <T> T xml2Obj(File file, Class<T> c)
    {
        T t = null;
        if (file == null || !file.exists() || file.isDirectory())
        {
            return null;
        }
        try
        {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T)unmarshaller.unmarshal(file);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return t;
    }
}
